package cn.sylinx.hbatis.db.mapper;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import cn.sylinx.hbatis.db.mapper.anno.PrimaryKey;
import cn.sylinx.hbatis.db.mapper.anno.Table;
import cn.sylinx.hbatis.kit.StrKit;
import cn.sylinx.hbatis.plugin.model.ModelCacheManager;
import cn.sylinx.hbatis.plugin.model.ModelFabric;

public class ModelBuilder {

	public static <T> InsertMapper<T> buildInsertMapper(T t) {

		final Class<?> clz = t.getClass();
		final ModelFabric mf = getModelFabric(clz);
		final String table = mf.getTableName();
		if (StrKit.isBlank(table)) {
			throw new IllegalArgumentException("数据库表为空");
		}

		InsertMapper<T> mapper = new InsertMapper<T>() {

			@Override
			public String getTableName() {
				return table;
			}

			@Override
			public Map<String, String> getJavaToJdbcMapper() {

				return mf.getAttrMapping();
			}
		};

		return mapper;
	}

	public static <T> UpdateMapper<T> buildUpdateMapper(T t) {

		final Class<?> clz = t.getClass();
		final ModelFabric mf = getModelFabric(clz);
		final String table = mf.getTableName();

		if (StrKit.isBlank(table)) {
			throw new IllegalArgumentException("数据库表为空");
		}

		final PrimaryKey pks = mf.getPrimaryKey();

		UpdateMapper<T> mapper = new UpdateMapper<T>() {

			@Override
			public String getTableName() {
				return table;
			}

			@Override
			public Map<String, String> getJavaToJdbcMapper() {

				return mf.getAttrMapping();
			}

			@Override
			public List<String> getPrimaryKeyFieldNameList() {

				List<String> pklist = new ArrayList<String>();

				if (pks != null) {

					String[] pkArray = pks.value();

					for (String pk : pkArray) {
						if (StrKit.isNotBlank(pk)) {
							pklist.add(pk);
						}
					}
				}

				if (pklist.isEmpty()) {
					pklist.add("id");
				}

				return pklist;
			}
		};
		return mapper;
	}

	public static <T> DeleteMapper<T> buildDeleteMapper(T t) {

		final Class<?> clz = t.getClass();

		final ModelFabric mf = getModelFabric(clz);

		final String table = mf.getTableName();

		if (StrKit.isBlank(table)) {
			throw new IllegalArgumentException("数据库表为空");
		}

		final PrimaryKey pks = mf.getPrimaryKey();

		DeleteMapper<T> mapper = new DeleteMapper<T>() {

			@Override
			public String getTableName() {
				return table;
			}

			@Override
			public Map<String, String> getJavaToJdbcMapper() {

				return mf.getAttrMapping();
			}

			@Override
			public List<String> getPrimaryKeyFieldNameList() {

				List<String> pklist = new ArrayList<String>();

				if (pks != null) {

					String[] pkArray = pks.value();

					for (String pk : pkArray) {
						if (StrKit.isNotBlank(pk)) {
							pklist.add(pk);
						}
					}
				}

				if (pklist.isEmpty()) {
					pklist.add("id");
				}

				return pklist;
			}
		};

		return mapper;
	}

	/**
	 * 通过类注解获取QueryMapper对象
	 * 
	 * @param clz
	 *            Class
	 * @return QueryMapper
	 */
	public static <T> QueryMapper<T> buildQueryMapper(final Class<T> clz) {

		final ModelFabric mf = getModelFabric(clz);

		if (mf.isMappingEmpty()) {
			return null;
		}

		QueryMapper<T> t = new QueryMapper<T>() {
			@Override
			public Map<String, String> getJdbcToJavaMapper() {

				return mf.getJdbcMapping();
			}

			@Override
			public Class<T> getValueObjectClass() {

				return clz;
			}
		};

		return t;
	}

	public static final void buildColumnNamesAndTypes(ResultSetMetaData rsmd, String[] labelNames, int[] types)
			throws SQLException {
		for (int i = 1; i < labelNames.length; i++) {
			labelNames[i] = rsmd.getColumnLabel(i);
			types[i] = rsmd.getColumnType(i);
		}
	}

	public static List<Field> getObjectAllFieldsWithcache(Class<?> cclz) {

		ModelFabric mf = getModelFabric(cclz);
		return mf.getFields();
	}

	public static Map<String, Field> getObjectAllFieldsMapWithcache(Class<?> cclz) {

		ModelFabric mf = getModelFabric(cclz);
		return mf.getFieldMap();
	}

	public static List<Field> getObjectAllFields(Class<?> cclz) {

		List<Field> fields = new ArrayList<Field>();

		Field[] fs = cclz.getDeclaredFields();

		if (fs != null && fs.length > 0) {

			for (Field f : fs) {

				String modifiers = Modifier.toString(f.getModifiers());

				if (!modifiers.contains("final") && !modifiers.contains("static") && !modifiers.contains("transient")
						&& !f.getName().equals("context")) {

					fields.add(f);
				}
			}
		}

		Class<?> pclz = cclz.getSuperclass();

		if (pclz != null && !pclz.isInterface()) {

			List<Field> fds1 = getObjectAllFields(pclz);
			if (fds1 != null && !fds1.isEmpty()) {
				fields.addAll(fds1);
			}
		}

		return fields;

	}

	public static Map<String, Field> getObjectAllFieldsMap(Class<?> cclz) {

		Map<String, Field> fields = new HashMap<String, Field>();

		Field[] fs = cclz.getDeclaredFields();

		if (fs != null && fs.length > 0) {

			for (Field f : fs) {

				String modifiers = Modifier.toString(f.getModifiers());

				if (!modifiers.contains("final") && !modifiers.contains("static") && !modifiers.contains("transient")
						&& !f.getName().equals("context")) {
					// context 关键字

					fields.put(f.getName(), f);
					fields.put(f.getName().toUpperCase(), f);
				}
			}
		}

		Class<?> pclz = cclz.getSuperclass();

		if (pclz != null && !pclz.isInterface()) {

			Map<String, Field> fds1 = getObjectAllFieldsMap(pclz);
			if (fds1 != null && !fds1.isEmpty()) {
				fields.putAll(fds1);
			}
		}

		return fields;

	}

	public static ModelFabric getModelFabric(String clzStr) {
		return ModelCacheManager.get().getModelFabric(clzStr);

	}

	public static String getModelTable(Class<?> clz) {
		final Table table = clz.getAnnotation(Table.class);
		return table != null ? table.value() : null;
	}

	public static ModelFabric getModelFabric(Class<?> clz) {
		return ModelCacheManager.get().getModelFabric(clz);
	}

	public static String buildColumnsByExcluded(Class<?> clz, List<String> excludedColumns) {

		ModelFabric mf = getModelFabric(clz);
		Map<String, String> attrs = mf.getAttrMapping();
		Set<String> columns = new HashSet<String>();
		Set<Entry<String, String>> kvsets = attrs.entrySet();
		for (Entry<String, String> entry : kvsets) {
			if (excludedColumns.contains(entry.getKey()) || excludedColumns.contains(entry.getValue())
					|| excludedColumns.contains(entry.getValue().toLowerCase())) {
				continue;
			}
			columns.add(entry.getValue().toUpperCase());
		}

		StringBuilder sb = new StringBuilder();
		columns.forEach(k -> sb.append(k).append(","));
		if (sb.length() > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}
}
